var schemeContentHeight = null;

function loadAnalysis(type, call) {
    if (schemeContentHeight == null) { // 记录原始高度,避免被统计页面撑开
        schemeContentHeight = $(".content")[0].style.minHeight;
    } else {
        $(".content")[0].style.minHeight = schemeContentHeight; // 之后每次都赋予原始高度
    }

    var url = "";
    var projectCode = $("#projectCode").val();
    var schemeCode = $("#schemeCode").val();

    $("#a_heat").removeAttr("class");
    $("#a_route").removeAttr("class");
    $("#a_focus").removeAttr("class");
    $("#a_grid").removeAttr("class");
    $("#a_aoi").removeAttr("class");
    $("#a_statistic").removeAttr("class");

    $("#analysisType").val(type);

    if (type == AnalysisTypeEnum.HEATMAP) {
        url = "analysis_heatmap.action";
        $("#a_heat").attr("class", "on");
    } else if (type == AnalysisTypeEnum.ROUTEMAP) {
        url = "analysis_routemap.action";
        $("#a_route").attr("class", "on");
    } else if (type == AnalysisTypeEnum.FOCUSMAP) {
        url = "analysis_focusmap.action";
        $("#a_focus").attr("class", "on");
    } else if (type == AnalysisTypeEnum.GRIDMAP) {
        url = "analysis_gridmap.action";
        $("#a_grid").attr("class", "on");
    } else if (type == AnalysisTypeEnum.AOI) {
        url = "analysis_aoi.action";
        $("#a_aoi").attr("class", "on");
    } else if (type == AnalysisTypeEnum.STATISTIC) {
        url = "statistic_load.action";
        $("#a_statistic").attr("class", "on");
    } else {
        return;
    }

    loading();

    ajaxLoading($("#analysisContainer"), url, {
        "projectCode": projectCode,
        "schemeCode": schemeCode
    }, function (status) {
        if (call) {
            call(status);
        } else {
            closeLoad();
            loadErrorFunction(status);
        }
    });
}

function retIndex() {
    location.href = "analysis_index.action"; // 错误时回到云分析页面
}

function loadErrorFunction(status) {
    if (status != "success") {
        popalert({
            "content": "系统忙，请稍后重试！",
            "icon": "warning",
            "ok": "retIndex()",
            "close": "retIndex()",
            "okVal": "确定",
            "cancel": false
        });
    }
}

function chooseMaterial() {
    var projectCode = $("#projectCode").val();
    var schemeCode = $("#schemeCode").val();
    var url = "analysis_popMaterial.action?projectCode=" + projectCode + "&schemeCode=" + schemeCode;

    popup('选择测评素材', url, 650, 500, 'chooseMaterial', true);
}

/**
 * 创建新的坐标值
 *
 * @param point
 */
function newPointModel(point) {
    // if (point) {
    //     var off = getOffset();
    //     var result = point.map(function (p) {
    //         var cd = convertCoordinate(p.x, p.y, off);
    //         if (p.time) {
    //             cd.time = p.time;
    //         } else if (p.fixDur) {
    //             cd.fixDur = p.fixDur;
    //             cd.fixStart = p.fixStart;
    //             cd.LPS = p.LPS;
    //             cd.RPS = p.RPS;
    //         }
    //         return cd;
    //     });
    //     return result;
    // }
    return point;
}

/**
 * 获取坐标偏移量
 */
function getOffset() {
    var me = $('#displayArea').offset();
    var body = $('body');
    // 图片缩放比例
    var rt = {offX: 0, offY: 0};
    rt.offX = (window.screen.width - body.width() + me.left) * displayRate;
    rt.offY = (window.screen.height - body.height() + me.top) * displayRate;
    return rt;
}

/**
 * 转换坐标数据
 *
 * @param x
 * @param y
 * @param off
 */
function convertCoordinate(x, y, off) {
    var rt = {x: x, y: y};
    if (x) {
        //坐标差在和x进行想加
        rt.x += off.offX;
    }
    if (y) {
        //坐标差在和x进行想加
        rt.y += off.offY;
    }
    return rt;
}

/**
 * 加载完成后初始化
 */
function loadInit(type) {
    loadAnalysis(type || AnalysisTypeEnum.ROUTEMAP, function (status) {
        $('.down-load-all').remove();
        loadErrorFunction(status);
        this.bindMenuClick();
    });
}

/**
 * 保存分析图片
 */
function cropImage(call) {

    /** 1. 新建画布对象 */
    var width = $("#displayArea").width();
    var height = $("#displayArea").height();

    var crop_canvas = document.createElement('canvas'); // 创建一个画布,宽/高与分析图画布的宽/高一致
    crop_canvas.width = width;
    crop_canvas.height = height;

    crop_canvas.getContext('2d').drawImage($("#mainImage")[0], $("#mainImage").offset().left - $("#displayArea").offset().left, $("#mainImage").offset().top - $("#displayArea").offset().top,
        $("#mainImage").width(), $("#mainImage").height()); // 背景图,宽/高是相对displayArea的

    if ($("canvas").length > 0) {
        crop_canvas.getContext('2d').drawImage($("canvas")[0], 0, 0, width, height); // 分析图画布
    }

    var filename = (new Date()).getTime() + '.jpg'; // 文件名

    if (call) {
        var image = crop_canvas.toDataURL('image/jpeg', 1.0);
        call({image: image, filename: filename});
        return;
    }

    /** 2. 将画布内容保存为文件,并直接弹出下载 */
    var image = crop_canvas.toDataURL("image/octet-stream");

    // 未定义函数表示直接下载
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = image;
    save_link.download = filename;

    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}


/**
 * 下载所有数据
 */
var downAll = ['heatmap', 'routemap', 'focusmap', 'gridmap', 'interestarea'];

function downloadAll(type, call, loading) {
    if (!loading) {
        // 不要加载框
        window.hasOpenLoading = false;
        // $('body').prepend('<div class="down-load-all"><div class="txt">数据分析中，请稍后...</div></div>');
    }

    var data = {
        images: []
    };

    data.userCode = $("#userCode").val();
    data.projectCode = $("#projectCode").val();
    data.schemeCode = $("#schemeCode").val();
    data.materialCode = $("#materialCode").val();
    data.materialType = $("#materialType").val();

    loadAnalysisAll(0, data, function (dt) {
        saveFile(dt);
        call(type);
    });
}

/**
 * 加载或有的图片资源
 *
 * @param i
 * @param data
 * @param call
 */
function loadAnalysisAll(i, data, call) {
    if (i >= downAll.length) {
        call(data);
        return;
    }
    var a = downAll[i];
    loadAnalysis(a, function (status) {
        if (status === 'success') {
            setTimeout(function () {
                cropImage(function (img) {
                    data.images.push({
                        analysisType: a,
                        base: encodeURIComponent(img.image)
                    });
                    loadAnalysisAll(i + 1, data, call);
                });
            }, 1000);
        } else {
            setTimeout(function () {
                loadAnalysisAll(i + 1, data, call);
            }, 1000);
        }
    });
}

/**
 * 提交后台进行文件存储
 */
function saveFile(data) {
    // 获取选中的单元格内容数据
    var checkBox = getAlreadyCheck(true);
    if (checkBox && checkBox.length > 0) {
        var check = $(checkBox[checkBox.length - 1]);
        data.checkBoxCode = check.val();
        data.checkBoxName = check.data('name');
    } else {
        data.checkBoxCode = "";
        data.checkBoxName = "";
    }

    window.save_file_data = data;

    var url = 'auto_save.action?_time=' + new Date().getTime();
    callJsonDataWithMethod(url, {data: JSON.stringify(data)}, function () {
        // 不处理
    }, function () {
        popalert({
            "content": "快速保存图片失败",
            "icon": "warning",
            "okVal": "确定",
            "cancel": false
        });
    });
}

/**
 * 绑定主体信息
 */
function bindMenuClick() {
    $('#menu_tab').off('click', 'a');
    $('#menu_tab').on('click', 'a', function () {
        var me = $(this);
        var type = me.data('type');
        if (type !== 'down') {
            loadAnalysis(type);
        } else {
            downloadAll(type, function (type) {
                loadInit(type);
                window.hasOpenLoading = true;
            });
        }
    });
}

/**
 * 设置选中的结果数据
 */
function setAlreadyValue(value) {
    if (getAnalysisRadio()) {
        $("#alreadyRadio").val(value);
    } else {
        $("#alreadyCheckboxs").val(value);
    }
}

/**
 * 获取本次选中的结果数据
 */
function getAlreadyValue() {
    if (getAnalysisRadio()) {
        return $("#alreadyRadio").val();
    } else {
        return $("#alreadyCheckboxs").val();
    }
}

/**
 * 判断是否获取单选
 */
function getAnalysisRadio() {
    var type = $("#analysisType").val();
    var mType = $("#materialType").val();
    return type === AnalysisTypeEnum.ROUTEMAP || mType === MaterialTypeEnum.RECORD;
}

/**
 * 获取选中的对象数据
 */
function getAlreadyCheck(checked) {
    if (checked) {
        return $("#resultBody").find("input.analysis-type-item:checked");
    } else {
        return $("#resultBody").find("input.analysis-type-item");
    }
}

/**
 * 默认选中所有素材加载执行
 *
 * @param data
 * @param index
 */
function selectMaterialAll(type, data, loading, index, call) {
    if (index >= data.length) {
        call(type);
        return;
    }
    loading.append(90 / data.length);
    // 获取第一个
    $("#materialCode").val(data[index].Code);
    $("#materialType").val(data[index].Type);
    downloadAll(type, function (type) {
        selectMaterialAll(type, data, loading, index + 1, call);
    }, true);
}

$(function () {
    $('#menu_tab').off('click', 'a');
    var initType = $("#analysisType").val();
    /** load消息 */
    setTimeout(function () {
        // 获取默认值
        var iMaterialCode = $("#materialCode").val();
        var iMaterialType = $("#materialType").val();

        // 通过ajax请求是否存在需要保存的素材信息

        var projectCode = $("#projectCode").val();
        var schemeCode = $("#schemeCode").val();
        var url = '/analysis/analysis_findM.action?_time=' + new Date().getTime();
        url += '&projectCode=' + projectCode;
        url += '&schemeCode=' + schemeCode;
        $.ajax({
            url: url,
            dataType: "json",
            error: function () {
                loadInit(initType);
            },
            success: function (json) {
                // 循环获取数据信息
                var data = json.data || [];
                // 不要加载框
                window.hasOpenLoading = false;
                var loading = new DownLoading();
                if (data.length > 1) {
                    loading.start(10);
                } else {
                    loading.config.enlarge = 48.7;
                }
                selectMaterialAll(initType, data, loading, 0, function (type) {
                    // 保持原位置
                    var xt = data[0] || {};
                    $("#materialCode").val(iMaterialCode || xt.Code);
                    $("#materialType").val(iMaterialType || xt.Type);

                    loading.stop(function () {
                        loadInit(type);
                        window.hasOpenLoading = true;
                    });
                });
            }
        });
    }, 500);
});